package com.batsoft.trade.disruptor.opp;

import com.batsoft.trade.entity.OrderData;
import com.batsoft.trade.entity.OrderDataDown;
import com.gomyb.redis.RedisService;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;

import java.math.BigDecimal;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 * 2019/8/29 15:32
 */
@Slf4j
public class OppDataEventHandler implements WorkHandler<OppDataEvent> {

    @Autowired
    private RedisService redisService;

    @Override
    public void onEvent(OppDataEvent event) throws Exception {
        redisService.execute(new SessionCallback<Object>() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                OrderData oData = event.getValue().getOData();
                try {
                    switch (oData.getHandleType()) {
                        case BUY_OPEN_MORE:

                            break;
                        case BUY_FLAT_EMPTY:


                            break;
                        case SELL_FLAT_MORE:

                            break;
                        case SELL_OPEN_EMPTY:
                            if (oData.getCount().compareTo(BigDecimal.ZERO) == 0) {
                                OrderDataDown oDataDown = calculateFee(oData);
//                                operations.opsForHash().delete(RedisKey.ORDER_WAIT_ORDER, oData.getOrderNum());
//                                operations.opsForHash().put(RedisKey.MATCH_SUCCESS_ORDER, oData.getOrderNum(), oDataDown);
                                // 持仓统计


                                // 扣除手续费（不够时扣为0，剩余延时扣取）
                            } else {
//                                operations.opsForHash().put(RedisKey.ORDER_WAIT_ORDER, oData.getOrderNum(), oData);
                            }
                            break;
                        default:
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("对手计算失败~", e);
                }
                return operations.exec();
            }
        });

    }

    /**
     * 手续费计算
     * (成交合约张数 * 合约面值 / 成交均价) * 费率
     */
    private OrderDataDown calculateFee(OrderData oData) {
        BigDecimal mean = oData.getTotalMoney().divide(oData.getCountAll());
        BigDecimal fee = oData.getCountAll().multiply(oData.getFaceValue()).divide(mean).multiply(oData.getFeeRatio());
        OrderDataDown oDataDown = new OrderDataDown();
        BeanUtils.copyProperties(oData, oDataDown);
        oDataDown.setFee(fee);
        return oDataDown;
    }
}
